package com.example.function.integration.utils;

/**
 * @Description：利率计算工具类
 * @Author： fengcheng
 * @Date： 2024/10/10 14:40
 */
public class RatesComputeUtils {

    /**
     * 使用牛顿迭代法计算月利率
     *
     * @param loanAmount     贷款总额
     * @param monthlyPayment 每月还款额
     * @param periods        还款期数（月）
     * @return 月利率
     */
    private static double findMonthlyInterestRate(double loanAmount, double monthlyPayment, int periods) {
        double guess = 0.01; // 初始猜测值为1%
        double tolerance = 1e-8; // 容忍误差
        double error = Double.MAX_VALUE; // 初始化误差
        while (error > tolerance) {
            double numerator = loanAmount * Math.pow(1 + guess, periods) - monthlyPayment * periods;
            double denominator = periods * loanAmount * Math.pow(1 + guess, periods - 1) - loanAmount;
            guess -= numerator / denominator;
            error = Math.abs(numerator / denominator);
        }
        return guess;
    }

    public static void main(String[] args) {
        double loanAmount = 124000; // 贷款总额
        double monthlyPayment = 3622.48; // 每月还款额
        int periods = 36; // 还款期数（月）
        double monthlyInterestRate = findMonthlyInterestRate(loanAmount, monthlyPayment, periods);
        double annualInterestRate = monthlyInterestRate * 12;
        System.out.println("月利率为：" + monthlyInterestRate);
        System.out.println("年利率为：" + annualInterestRate);
    }
}
